package com.taskScheduler;

import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.taskScheduler.task.FileTransferTask;
import com.taskScheduler.utils.TaskState;

public class TaskScheduler {
	private final int TASK_QUEUE_SIZE;
	private BlockingQueue<FileTransferTask> queue;
	private HashMap<Long, TaskState> excutingTaskStateMap;

	public TaskScheduler(int taskQueueSize) {
		this.TASK_QUEUE_SIZE = taskQueueSize;
		this.queue = new ArrayBlockingQueue<FileTransferTask>(
				this.TASK_QUEUE_SIZE);
		this.excutingTaskStateMap = new HashMap<Long, TaskState>();
	}

	public void excuteTaskOnRemoteMachine() {
		while (!queue.isEmpty()) {
			FileTransferTask fileTransferTask = queue.poll();
			boolean can = canExcute(fileTransferTask);
			if (can) {
				// excute this task on remote machine
				// by three methods: web service, rpc ,message queue
				// to do

				// add the task here, in case the excution before may throw
				// exception
				this.excutingTaskStateMap.put(fileTransferTask.getTaskId()
						.get(), TaskState.SCHEDULED);
			} else {
				try {
					queue.put(fileTransferTask);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					// 以后会写入日志，并将此任务放入失败队列
					e.printStackTrace();
				}
			}
		}
	}

	private boolean canExcute(FileTransferTask fileTransferTask) {
		return true;
	}

	public void updateTaskState(long taskId) {
		// get the task state form remote machine and update it in the
		// excutingTaskStateMap
	}

	public TaskState queryTaskState(long taskId) {
		// look up the task state in the excutingTaskStateMap, if has, return its state,
		// else query form the database or others.
	
		return TaskState.SUCESS;
	}
}
